package com.nicolasprof.profgallery.controls {
	import com.nicolasprof.profgallery.Engine;

	import flash.display.DisplayObject;
	import flash.display.InteractiveObject;
	import flash.display.Sprite;
	import flash.events.Event;

	/**
	 * @author Nicolas Prof
	 */
	public class Controls extends Sprite {

		private var _engine : Engine;
		protected var _uiCollection : Object;

		
		public function Controls($engine : Engine) {
			_engine = $engine;
			this.addEventListener(Event.ADDED_TO_STAGE, onAdded);
		}		
		public function disableSlideshow() : void {
			var ss : UIComponent = getUIComponent(UIComponent.BUTTON_SLIDESHOW);
			if(ss != null) {
				ss.apply(false);
			}
		}
		protected function init() : void {
			var config : XML = Engine.CONFIG_XML;
			_uiCollection = {};
			
			//Actions
			registerUI();
			
			this.x = config.controls.@posX;
			this.y = config.controls.@posY;
		}
		
		protected function getUIComponent($name : String) : UIComponent {
			return _uiCollection[$name];
		}	
		internal function next() : void {
			_engine.selectThumbnail(1);
		}
		internal function previous() : void {
			_engine.selectThumbnail(-1);
		}
		protected function registerUI() : void {
			var list : Object = UIComponent.getList();
			var uiComponent : DisplayObject;
			for(var ui: String in list) {
				uiComponent = this.getChildByName(ui);
				if(uiComponent != null){
					_uiCollection[ui] = new UIComponent(uiComponent as InteractiveObject, this);
				}
			}
		}	
		internal function showMenu() : void {
			_engine.buildMenu();
		}	
		internal function toggleSlideshow() : void {
			_engine.toggleSlideshow();
		}	
		public function updatePosition($current: int, $all: int) : void {
			var current : UIComponent = getUIComponent(UIComponent.TEXTFIELD_CURRENT);
			if(current != null) {
				current.apply($current);
			}
			var all : UIComponent = getUIComponent(UIComponent.TEXTFIELD_ALL);
			if(all != null) {
				all.apply($all);
			}
		}		
		/**
		 * Events
		 */
		private function onAdded(e : Event) : void {
			this.removeEventListener(Event.ADDED_TO_STAGE, onAdded);
			init();
		}
		/*
		private function onControlGallery(e : ControlEvent) : void {
			_engine.menuComponent.build();
		}*/
	}
}
